package com.meituan.verintreport.task;

import com.meituan.verintreport.db.dao.FormComponentHierarchyMapper;
import com.meituan.verintreport.db.dto.FormComponentHierarchyDto;
import com.meituan.verintreport.db.verint.VerintBaseTableDao;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


/**
 * 全量数据同步
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "base-table.form-component-hierarchy")
public class BaseTableTaskFormComponentHierarchy extends BaseTableTask {
    @Resource
    private FormComponentHierarchyMapper formComponentHierarchyMapper;

    @Resource
    private VerintBaseTableDao verintBaseTableDao;

    /**
     * 全量数据同步 每天 12：10
     */
    @Scheduled(cron = "${base-table.form-component-hierarchy.cron}")
    public void execute() {

        if (!isEnable()) {
            return;
        }

        boolean shouldContinue;

        Integer rs = formComponentHierarchyMapper.truncate();
        log.info("remove {} data",rs);
        int pageIndex = 0;
        int pageSize = 1000;
        do {
            shouldContinue = false;

            List<FormComponentHierarchyDto> records = verintBaseTableDao.getFormComponentHierarchyList(pageIndex, pageSize);
            log.info("got {} records", records.size());
            if (records.size() == 1000) {
                shouldContinue = true;
            }

            for (FormComponentHierarchyDto record : records) {
                try {
                    formComponentHierarchyMapper.insert(record);
                } catch (Exception ex) {
                    log.error("Add GroupsToUser to db exception.", ex);
                }
            }

            pageIndex += pageSize;
        }
        while (shouldContinue);
    }
}
